package com.milk.nettylearn.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static com.milk.nettylearn.nio.ByteBufferUtil.debugRead;

@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        ByteBuffer buffer = ByteBuffer.allocate(100);
        serverSocketChannel.bind(new InetSocketAddress(8080));

        List<SocketChannel> list = new ArrayList<>();
        while (true) {
            log.debug("connecting .....");
            SocketChannel socketChannel = serverSocketChannel.accept();
            log.debug("connected .....");
            list.add(socketChannel);

            for (SocketChannel channel : list) {
                log.debug("wait read");
                channel.read(buffer);
                // 转换为读模式
                buffer.flip();
                debugRead(buffer);
                // 转换为读模式
                buffer.clear();
                log.debug("read after");
            }

        }
    }
}
